var amapFile = require('../../libs/amap-wx.js');
var util = require('../../libs/util.js');
var log = require('../log.js');
var amap, mapCtx;
var app = getApp();
var getLBSResult = false;
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    submiting: false,
    orderId: "",
    driverId: "",
    vehicleId: "",
    shopId: '',
    guid: '',
    app_gps_first: false,
    iotbox: "",
    tpAlarm: "",
    delivery_mile: 0,
    delivery_time: 0,
    current_order_number: 0,
    middle_height: "100vh",
    client_width: 0,
    client_height: 0,
    d_mile: 0,
    shop_number: 0,
    d_duration: 0,
    dd_hour: 0,
    dd_minute: 0,
    temperature: 0,
    tempState: "temp-off",
    humidity: 0,
    latitude: 0, //纬度 
    longitude: 0, //经度 
    speed: 0, //速度 
    accuracy: 16, //位置精准度 
    navLat: 0, //导航纬度 
    navLon: 0, //导航经度 
    markers: [],
    polyline: [],
    controls: [],
    "include-points": [],
    delivery_data: [],
    current_status: false,
    current_status_text: "",
    //delivery_limittime: "",
    delivery_time_text_show: false,
    delivery_time_text: "00:00",
    changeDeliveryPointBtn: false,
    changeDeliveryPointList: false,
    spd_height: 100,
    select_point_data: [],
    shop_reposition: false,
    shop_contact: false,
    supervision_contact: false,
    shop_picture: true,
    iot_box_on: false,
    delivery_item_form: false,
    deliveryImageList: [],
    deliveryImageListCompress: [],
    mapHidden: false,
    form_rule_data: "",
    is_agree_requirement: false,
    is_agree_undertaking: false,
    delivery_package: false,
    loadingRule: [],
    target_address: "暂无地址信息",
    target_distance: "距离目的地里程和耗时未知",
    tollfee: 0,
    tollfeeImgList: [],
    parkingfee: 0,
    parkingfeeImgList: [],
    deliveryDocsImgList: [],
    tollfeeImgListCompress: [],
    parkingfeeImgListCompress: [],
    deliveryDocsImgListCompress: [],
    delivery_exception: 0,
    delivery_score: 100,
    packageList: [],
    goodsList: []
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onReady: function (e) {
    mapCtx = wx.createMapContext('map');
  },
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({
      "title": app.appName + "--司机业务端"
    });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          middle_height: res.windowHeight - 102,
          client_width: res.windowWidth,
          client_height: res.windowHeight
        });
      }
    });
    that.setData({
      orderId: e.id,
      server: app.server,
      price_driver_show: app.globalData.price_driver_show
    });

    that.getLocation();
    //地图初始化
    that.initMap(this.data.orderId);

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          middle_height: res.windowHeight - 102
        });
      }
    });

    // app.socket.on('delivery', function (data) {
    //   console.log(data)
    //   if (data.delivery == that.data.orderId) {
    //     wx.showModal({
    //       title: '温馨提示',
    //       content: data.content,
    //       showCancel: false,
    //       success(res) {
    //         if (res.confirm) {
    //           if (data.action == 'restart') {
    //             wx.redirectTo({
    //               url: '/pages/driver/currentOrder?id=' + that.data.orderId
    //             })
    //           }
    //         }
    //       }
    //     })
    //   }
    // });
  },
  onShow: function (e) {

  },
  getLocation(callback) {
    var that = this;
    //获取手机定位坐标
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(res.latitude)
        var latitude = res.latitude;
        var longitude = res.longitude;
        that.setData({
          longitude: longitude,
          latitude: latitude
        });
        if (callback) {
          callback(longitude, latitude)
        }
      }
    });
  },
  regionchange: function (res) {
    var that = this;
    mapCtx.getCenterLocation({
      success: function (res) {
        var y = res.longitude;
        var x = res.latitude;
        that.setData({
          locationLongitude: y,
          locationLatitude: x
        })
      }
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    var that = this;
    if (e.currentTarget.dataset.target == 'goodsList') {
      util.getData("/atapi/delivery/process/getCurrentOrderGoodsList", {
        goodsList: that.data.currentPoint.goodsList
      }, function (res, error) {
        console.log(res);
        console.log(error)
        if (error) {
          wx.hideLoading();
          wx.showToast({
            title: '申请失败',
            image: '/images/wrong.svg',
            duration: 2000
          });
          return false;
        }
        if (res.data.success) {
          that.setData({
            goodsList: res.data.data
          })
        }
      });
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  iotBox: function (driver_status) {
    if (driver_status == "end") {
      return false;
    };
    var that = this;
    //socket
    // app.socket.on('connect', function () {
    //   console.log('socket connect');
    // });
    //app.socket.emit('deliveryStart', { iotbox: that.data.iotbox, vehicle: that.data.vehicleId, order: that.data.orderId });
    // else{
    //   socket.emit('vehicleEnd', { iotbox: that.data.iotbox });
    // }
    //定时关闭，以检测盒子是否在线
    setInterval(function () {
      //智冷盒状态
      that.setData({
        iot_box_on: false
      })
    }, 300000);
    console.log(that.data.iotbox)
    // app.socket.on(that.data.iotbox, function (data) {
    //   console.log(data)
    //   if (data.iotType == "NT") {// || data.iotType == "TP"
    //     that.setData({
    //       temperature: data.temperature || '__',
    //       tempState: (Number(data.temperature) > Number(that.data.tpAlarm) ? 'temp-warn' : 'temp-on')
    //     });
    //     //app.globalData.temperature = data.temperature;
    //     //智冷盒状态
    //     that.setData({
    //       iot_box_on: true
    //     })
    //     //wx.setStorage({ key: that.data.orderId + '_temperature', data:Number(data.temperature)});
    //   } else if (data.iotType == "HR") {
    //     that.setData({
    //       humidity: data.humidity || '__'
    //     });
    //     //app.globalData.humidity = data.humidity;
    //     //wx.setStorage({ key: that.data.orderId + '_humidity', data: Number(data.humidity)});
    //   } else if (data.iotType == "PS") {
    //     app.globalData.latitude = data.latitude;
    //     app.globalData.longitude = data.longitude;
    //     //console.log(data)
    //     //if (!that.data.app_gps_first){
    //     that.setCurrentLocation(data.latitude, data.longitude, data.speed || 0, data.delivery_mile, data.delivery_time);
    //     //}
    //     //wx.setStorage({ key: that.data.orderId + '_gps', data: data.latitude + '_' + data.longitude + '|' + ((Number(data.delivery_mile) || 0) / 1000).toFixed(1) + '|' + (Number(data.delivery_time) || 0).toFixed(2)});
    //   };
    // });
  },
  appGps: function () {
    var that = this;
    if (that.timerId) {
      clearInterval(that.timerId);
      that.timerId = null;
      return;
    };
    that.timerId = setInterval(function () {
      wx.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标 
        // gcj02 是谷歌gps定位标准
        success: function (res) {
          //that.setCurrentLocation(res.latitude, res.longitude);
          //app.socket.emit('gps', { vehicle: that.data.vehicleId, order: that.data.orderId, iotbox: that.data.iotbox, iotType: 'PS', latitude: res.latitude, longitude: res.longitude });
        }
      })
    }, 3000)
  },
  setCurrentLocation: function (x, y, speed, delivery_mile, delivery_time) {
    var that = this;
    // var tempXY = that.data.polyline[0].points[that.data.polyline[0].points.length - 1];
    // if (tempXY) {
    //   var a = tempXY.latitude, b = tempXY.longitude;
    //   var dis = that.getDisance(a, b, x, y, that);
    //   dis = Number(dis.toFixed(5));
    //   // 原计划记录走过的路程，但是由于定位偏差较大，
    //   // 且没法获取偏差，导致结果差别很大，因此这想法基本被有限的API给废了
    //   if (dis >= 8) {
    //     dis += Number(that.data.distance);
    //     that.data.polyline[0].points.push({
    //       latitude: x,
    //       longitude: y
    //     });
    //     that.setData({
    //       distance: dis
    //     })
    //   }
    // } else {
    //   that.data.polyline[0].points.push({
    //     latitude: x,
    //     longitude: y
    //   });
    // };
    // that.data.polyline[0].points.push({
    //   latitude: x,
    //   longitude: y
    // });
    //console.log(((Number(delivery_mile) || 0) / 1000).toFixed(1))
    that.setData({
      delivery_mile: ((Number(delivery_mile) || 0) / 1000).toFixed(1),
      delivery_time: (Number(delivery_time) || 0).toFixed(2),
      speed: speed,
      longitude: y,
      latitude: x //,
      //polyline: that.data.polyline
    });
    //console.log(that.data.markers)
    mapCtx.translateMarker({
      markerId: 888,
      autoRotate: false,
      duration: 1,
      destination: {
        latitude: x,
        longitude: y
      }
    });
  },
  toRad: function (d) {
    return d * Math.PI / 180;
  },
  getDisance: function (lat1, lng1, lat2, lng2, that) {
    var dis = 0;
    var radLat1 = that.toRad(lat1);
    var radLat2 = that.toRad(lat2);
    var deltaLat = radLat1 - radLat2;
    var deltaLng = that.toRad(lng1) - that.toRad(lng2);
    var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
    return dis * 6371393;
  },
  initMap: function (id) {
    var that = this,
      controls = [];
    var markers = [],
      lalt = [];

    amap = new amapFile.AMapWX({
      key: 'ca20299a0d39dd8eccd23e561ba8be89'
    });

    wx.showLoading({
      title: '数据加载中...',
    });

    util.postData("/sys/shop/getDtsByDeliveryId/" + id, {}, function (res, error) {
      console.log(res)
      wx.hideLoading();
      setTimeout(function () {
        wx.hideLoading();
      }, 100)
      if (res.data.success && res.data?.result?.deliveryInfo?.length > 0) {
        var delivery_data = res.data.result.deliveryInfo[0]
        var point_data = res.data.result.deliveryListInfo
        var undertaking_data = [];
        var delivery_point = delivery_data.delivery_point; //当前配送点。W1,S2;W为发货点，S为收货点
        var delivery_sort = Number(delivery_data.delivery_sort); //当前配送序号。当前已配送点（==已配送数量）
        var delivery_status = delivery_data.driver_status; //配送状态。到达，装/卸货，结束
        var deliveryMode = delivery_data.deliveryMode; //配送模式，0：标准配送，1：拍照二维码

        wx.setNavigationBarTitle({
          "title": delivery_data.path_name
        });

        //计算配送状态
        var point_number_already = 0,
          all_point_number_already = 0,
          packageList = [],
          no_delivery_point = [];
        point_data = point_data.sort(function (a, b) {
          return Number(a.point_sort) > Number(b.point_sort);
        });
        for (var i = 0; i < point_data.length; i++) {
          if (moment(point_data[i].shop_time).isValid()) {
            point_data[i].shop_time_text = moment(point_data[i].shop_time).format('YYYY年MM月DD日 HH时mm分');
          } else {
            point_data[i].shop_time_text = '无';
          }
          if (point_data[i].picture == '' || point_data[i].picture == 'undefined' || point_data[i].picture == null) {
            point_data[i].picture_compress = []
            point_data[i].picture = []
          } else {
            point_data[i].picture_compress = String(point_data[i].picture_compress).split(',')
            point_data[i].picture = String(point_data[i].picture).split(',')
          }
          point_data[i].goodsInfo = point_data[i].goodsInfo || delivery_data.loadingrule;
          if (point_data[i].is_receive == 1 && point_data[i].type == 'shop') {
            point_number_already++;
          }
          if (point_data[i].is_receive == 1) {
            all_point_number_already++;
          }
          if (point_data[i].type == 'shop') {
            packageList.push({
              id: point_data[i].ID,
              name: point_data[i].name,
              shop: point_data[i].shop,
              package: point_data[i].package,
              unload_box: point_data[i].unload_box || 0,
              back_box: point_data[i].back_box || 0,
              return_package: point_data[i].return_package || 0,
              deliveryThirdParty_income: point_data[i].deliveryThirdParty_income || 0,
              deliveryThirdParty_pay: point_data[i].deliveryThirdParty_pay || 0,
              remark: point_data[i].remark,
              goodsInfo: point_data[i].goodsInfo,
              loadingRule: []
            });
          }
          if (point_data[i].type == 'shop' && point_data[i].is_delivery == 0) {
            no_delivery_point.push(point_data[i])
          }
        };
        //装载数量处理
        if (delivery_data.loadingrule) {
          for (var i = 0; i < packageList.length; i++) {
            var loadingRule = [],
              loading_rule = [];
            if (packageList[i].goodsInfo) {
              loading_rule = String(packageList[i].goodsInfo).split(",");
            } else {
              loading_rule = String(delivery_data.loading_rule || delivery_data.loadingrule).split(",");
            }
            console.log(packageList[i].goodsInfo)
            console.log(loading_rule)
            if (loading_rule.length > 0) {
              for (var j = 0; j < loading_rule.length; j++) {
                var _item = String(loading_rule[j]).split("|");
                loadingRule.push({
                  "id": "LDR" + j,
                  "name": _item[0],
                  "ratio": _item[1],
                  "number": _item[2]
                });
              }
              packageList[i].loadingRule = loadingRule;
            }
          }
        }

        var currentPoint = point_data[all_point_number_already] || {}; //即将配送点
        console.log('======currentPoint=======', all_point_number_already, point_data, currentPoint)
        for (var i = 0; i < point_data.length; i++) {
          if (point_data[i].is_receive == 0) {
            currentPoint = point_data[i];
            break;
          }
        }
        try {
          currentPoint.isreturn_ignore_distance_exception = false;
        } catch (e) {}
        if (delivery_data.isReturn == 1 && all_point_number_already == point_data.length) {
          currentPoint = point_data[0];
          currentPoint.isreturn_ignore_distance_exception = true;
        }
        // if(currentPoint.loading_time){
        //    currentPoint.loading_time = moment(currentPoint.loading_time).format('YYYY年MM月DD日 HH时mm分')
        // }
        //   if(currentPoint.shop_time){
        //     currentPoint.shop_time = moment(currentPoint.shop_time).format('YYYY年MM月DD日 HH时mm分')
        //  }
        that.setData({
          packageList: packageList,
          currentPoint: currentPoint,
          point_number_already: point_number_already,
          all_point_number_already: all_point_number_already
        });

        //配送完停车检查
        // if (!delivery_data.work_after_check) {
        //   wx.redirectTo({
        //     url: '/pages/driver/workAfterCheck'
        //   });
        //   return false;
        // }

        // var delivery_limittime, box_color;
        // for (var i = 0; i < res.data.data[3].length > 0; i++) {
        //   if (res.data.data[3][i].PARA_NAME == 'delivery_limittime') {
        //     delivery_limittime = JSON.parse(res.data.data[3][i].TEXT_VALUE);
        //   } else if (res.data.data[3][i].PARA_NAME == 'box_color') {
        //     box_color = String(res.data.data[3][i].TEXT_VALUE).split("|");
        //   }
        // }
        //设置是否有数据，和数据数量，显示在NavBar
        that.setData({
          orderId: delivery_data.ID,
          isReturn: delivery_data.isReturn,
          driverId: delivery_data.driver,
          vehicleId: delivery_data.vehicle,
          vehicle_type: delivery_data.vehicle_type,
          //current_order_number: res.data.data[0].length,
          delivery_data: delivery_data,
          point_data: point_data,
          no_delivery_point: no_delivery_point,
          path_name: delivery_data.path_name,
          delivery_point: delivery_point,
          delivery_sort: delivery_sort,
          delivery_status: delivery_status,
          point_number: point_data.length,
          driverPrice: (app.globalData.price_driver_show == 0 || (app.globalData.price_driver_show == 1 && delivery_data.price_driver_show == 0)) ? 0 : delivery_data.driverPrice,
          packages_expect: delivery_data.packages_expect || 0,
          packages: delivery_data.packages || 0,
          volume: delivery_data.volume || 0,
          unload_box: delivery_data.unload_box || 0,
          back_box: delivery_data.back_box || 0,
          return_package: delivery_data.return_package || 0,
          deliveryThirdParty_income: delivery_data.deliveryThirdParty_income || 0,
          deliveryThirdParty_pay: delivery_data.deliveryThirdParty_pay || 0,
          weight: delivery_data.weight || 0,
          goodsValue: delivery_data.goodsValue ? Number(delivery_data.goodsValue).toFixed(1) : 0,
          loading_time: moment(delivery_data.loading_time).format('YYYY年MM月DD日 HH时mm分'),
          remark: (delivery_data.remark && delivery_data.remark != 'undefined') ? delivery_data.remark : '无',
          iotbox: delivery_data.iot_box || 'WX' + app.globalData.vehicleId,
          tpAlarm: delivery_data.tp_alarm,
          //delivery_limittime: delivery_limittime,
          //box_color: box_color,
          latitude: delivery_data.latitude_current || 0,
          longitude: delivery_data.longitude_current || 0,
          temperature: '__',
          tempState: 'temp-off',
          humidity: '__',
          d_mile: delivery_data.total_mileage,
          d_duration: delivery_data.total_duration,
          delivery_mile: ((Number(delivery_data.delivery_mile) || 0) / 1000).toFixed(1),
          delivery_time: (Number(delivery_data.delivery_time) || 0).toFixed(2),
          deliveryMode: deliveryMode,
          receiving_order: delivery_data.receiving_order,
          //mapHidden: delivery_data.receiving_order == '0'?true:false,
          delivery_requirement: util.html_decode(delivery_data.delivery_requirement),
          is_undertaking: delivery_data.is_undertaking,
          undertaking_docs: util.html_decode(undertaking_data.docs),
          undertaking_update_date: util.html_decode(undertaking_data.update_date),
          undertaking_agree_text: undertaking_data.agree_text,
          work_before_check: delivery_data.work_before_check,
          work_after_check: delivery_data.work_after_check,
          tollfee: delivery_data.tollfee,
          tollfeeImgList: delivery_data.tollfee_docs ? util.arrayDeleteEmpty(delivery_data.tollfee_docs.split(",")) : [],
          tollfeeImgListCompress: delivery_data.tollfee_docs_compress ? util.arrayDeleteEmpty(delivery_data.tollfee_docs_compress.split(",")) : [],
          parkingfee: delivery_data.parkingfee,
          parkingfeeImgList: delivery_data.parkingfee_docs ? util.arrayDeleteEmpty(delivery_data.parkingfee_docs.split(",")) : [],
          parkingfeeImgListCompress: delivery_data.parkingfee_docs_compress ? util.arrayDeleteEmpty(delivery_data.parkingfee_docs_compress.split(",")) : [],
          deliveryDocsImgList: delivery_data.delivery_picture ? util.arrayDeleteEmpty(delivery_data.delivery_picture.split(",")) : [],
          otherfeeName: delivery_data.otherfeeName,
          otherfee: delivery_data.otherfee
        });
        wx.setStorage({
          key: "delivery_data",
          data: delivery_data
        });
        wx.setStorage({
          key: "point_data",
          data: point_data
        });
        // wx.setStorage({
        //   key: "delivery_limittime",
        //   data: delivery_limittime
        // });
        // wx.setStorage({
        //   key: "box_color",
        //   data: box_color
        // });

        //计算异常和评分
        // if (trace_data.length > 0) {
        //   var delivery_exception = 0;
        //   var delivery_score = 100;
        //   for (var i = 0; i < trace_data.length; i++) {
        //     console.log(trace_data[i].exception)
        //     if (trace_data[i].exception == 1) {
        //       delivery_exception++;
        //       delivery_score -= 10;
        //     }
        //   }
        //   that.setData({
        //     delivery_exception: delivery_exception,
        //     delivery_score: delivery_score
        //   })
        // }

        //配送结束
        // if (delivery_status == 'end') {
        //   wx.redirectTo({
        //     url: '/pages/driver/summary?id=' + delivery_data.ID
        //   });
        // }
        //拒绝订单
        if (delivery_data.receiving_order == '2') {
          wx.showModal({
            title: '温馨提示',
            content: '运单处于被拒单待处理状态',
            success(res) {
              wx.redirectTo({
                url: '/pages/driver/orderList'
              });
            }
          })
          return false;
        }
        //出车前检查
        if (app.globalData.work_before_check) {
          if (!delivery_data.work_before_check && delivery_data.receiving_order == '1' && delivery_data.is_undertaking == '1') {
            wx.redirectTo({
              url: '/pages/driver/work_check?type=beforecheck&plate=' + delivery_data.plate + '&vehicle=' + delivery_data.vehicle + '&id=' + that.data.orderId
            });
            return false;
          }
        }

        //智冷盒数据
        that.iotBox(delivery_status);


        //运单导航坐标
        if (currentPoint.coord) {
          var coord = String(currentPoint.coord).split(',');
          that.setData({
            navLat: coord[0],
            navLon: coord[1]
          });
        }
        //处理配送点
        for (var i = 0; i < point_data.length; i++) {
          var line_pos_top = 20 + 40 * i;
          var iconPath = "/images/tl_warehouse.png";
          //配送点是发货点--仓库
          if (point_data[i].type == 'warehouse') {
            //在地图上标出仓库位置
            var warehouse_img = "/images/warehouse.png";
            var iconPath = "/images/tl_warehouse.png";
            if (point_data[i].point_sort == delivery_sort) {
              warehouse_img = "/images/warehouse_current.png";
              iconPath = "/images/tl_warehouse_current.png";
            } else if (point_data[i].point_sort > delivery_sort) {
              warehouse_img = "/images/warehouse_already.png";
              iconPath = "/images/tl_warehouse_green.png";
            }
            markers.push({
              id: markers.length,
              title: point_data[i].name,
              iconPath: warehouse_img,
              width: 20,
              height: 23,
              latitude: point_data[i].latitude,
              longitude: point_data[i].longitude,
            });
            //构建流程按钮
            // controls.push({
            //   id: 10 + i,
            //   position: { left: that.data.client_width - 28, top: line_pos_top, width: 16, height: 16 },
            //   iconPath: iconPath,
            //   clickable: true
            // });



            //配送点是收货点--门店
          } else if (point_data[i].type == 'shop') {
            var iconPath = "/images/tl_shop.png";
            var shop_img = "/images/shop.png";
            if (point_data[i].point_sort == delivery_sort) {
              iconPath = "/images/tl_shop_current.png";
              shop_img = "/images/shop_current.png";
            } else if (point_data[i].point_sort > delivery_sort) {
              iconPath = "/images/tl_shop_already.png";
              shop_img = "/images/shop_already.png";
            }
            // con 
            markers.push({
              id: markers.length,
              title: point_data[i].name,
              iconPath: shop_img,
              width: 20,
              height: 23,
              latitude: point_data[i].latitude,
              longitude: point_data[i].longitude,
            });
          }
        }
        ///流程按钮////////////////////////////////////////////////////////////
        // that.setData({
        //   is_packing_do: _point.is_packing_do
        // });
        var _type = currentPoint.type,
          delivery_point, point_id = '',
          point_name = currentPoint.name;
        if (point_name && String(point_name).length > 12) {
          point_name = point_name.substr(0, 12) + '...';
        }
        if (_type == 'warehouse') {
          delivery_point = 'W' + currentPoint.warehouse;
          currentPoint.point_id = currentPoint.warehouse;
        } else {
          delivery_point = 'S' + currentPoint.shop;
          currentPoint.point_id = currentPoint.shop;
        }
        that.setData({
          currentPoint: currentPoint,
          delivery_point: delivery_point
        })
        //启动和智冷盒绑定
        if (delivery_status != 0 && delivery_status != "end") {
          console.log('deliveryStart')
          //app.socket.emit('deliveryStart', { iotbox: that.data.iotbox, vehicle: that.data.vehicleId, order: that.data.orderId });
        }

        if (all_point_number_already < point_data.length - 1 &&
          all_point_number_already > 0 &&
          point_data.length > 2) {
          that.setData({
            changeDeliveryPointBtn: true
          });
        }
        if (all_point_number_already < point_data.length) {
          that.setData({
            current_status: "reach",
            current_status_text: "到达：" + point_name
          });
          that.nextPointReachTime();
        } else {
          that.geocode();
        }

        if (delivery_data.driver_status == 'delivery_end') {
          if (delivery_data.isReturn == 1) {
            that.setData({
              current_status_text: "返仓：" + point_name
            });
            that.nextPointReachTime();
          } else {
            that.setData({
              current_status_text: "配送结束"
            });
          }
        }
        console.log(delivery_data.driver_status)



        ////////////////////////////////////////////////////////////////
        //在地图上标出车辆
        markers.push({
          id: 888,
          title: "配送车辆：" + delivery_data.plate + "\n司机：" + delivery_data.driverName,
          iconPath: "/images/vehicle.png",
          width: 26,
          height: 30,
          latitude: that.data.latitude,
          longitude: that.data.longitude
        });
        console.log(markers)
        //设置表示点和地图上配件
        that.setData({
          markers: markers,
          controls: controls
        });
        // mapCtx.includePoints({
        //   padding: [20],
        //   points: lalt
        // })
        that.getDrivingRoute();
      } else {
        that.setData({
          hasData: false
        })
      }
    });
  },
  getDrivingRoute: function () {
    var that = this;
    var pathData = that.data.markers;

    var lalt = [];

    var firstPOI, lastPOI, waypoints = new Array(),
      w_index = 0;
    for (var i = 0; i < pathData.length; i++) {
      if (i == 0) {
        firstPOI = pathData[i].longitude + ',' + pathData[i].latitude;
      } else if (i == pathData.length - 2) {
        lastPOI = pathData[i].longitude + ',' + pathData[i].latitude;
      } else if (i < pathData.length - 2) {
        waypoints[w_index] = pathData[i].longitude + ',' + pathData[i].latitude;
        w_index++;
      }
      if (pathData[i].id != 888) {
        lalt.push({
          latitude: pathData[i].latitude,
          longitude: pathData[i].longitude
        });
      }

    }
    that.setData({
      lalt: lalt
    });
    try {
      amap.getDrivingRoute({
        origin: firstPOI,
        destination: lastPOI,
        waypoints: waypoints.join(";"),
        strategy: 8,
        success: function (data) {
          var points = [];
          if (data.paths && data.paths[0] && data.paths[0].steps) {
            var steps = data.paths[0].steps;
            for (var i = 0; i < steps.length; i++) {
              var poLen = steps[i].polyline.split(';');
              for (var j = 0; j < poLen.length; j++) {
                points.push({
                  longitude: parseFloat(poLen[j].split(',')[0]),
                  latitude: parseFloat(poLen[j].split(',')[1])
                })
              }
            }
          }
          that.setData({
            polyline: [{
              points: points,
              color: "#0091ff",
              width: 3
            }]
          });
          if (data.paths[0] && data.paths[0].distance) {
            var duration = Number(data.paths[0].duration) + pathData.length * 30 * 60;
            var hourToTime = util.hourToTime(duration);
            that.setData({
              distance: (data.paths[0].distance / 1000).toFixed(1),
              duration: Number(duration).toFixed(2),
              duration_hour: hourToTime.hour,
              duration_minute: hourToTime.minute
            });
          }
          mapCtx.includePoints({
            padding: [10],
            points: lalt
          })
        },
        fail: function (info) {

        }
      })
    } catch (e) {}

  },
  callShop: function (e) {
    var that = this;
    var curp = that.data.currentPoint;
    var tel = curp.receiverphone || curp.supervision_phone;
    if (!tel) {
      wx.showToast({
        title: '暂无联系电话',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  callSupervision: function (e) {
    var that = this;
    var tel = that.data.point_data[Math.abs(that.data.delivery_sort - 1)].supervision_phone;
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },
  markertap: function (e) {
    console.log(e)
  },
  navigation: function (e) {
    if (this.data.navLat) {
      wx.openLocation({
        latitude: parseFloat(this.data.navLat),
        longitude: parseFloat(this.data.navLon),
        scale: 28
      })
    } else {
      wx.showToast({
        title: '没有坐标数据',
        image: '/images/wrong.svg',
        duration: 2000
      });
    }
  },
  changeDeliveryPoint: function () {
    var that = this;
    if (that.data.changeDeliveryPointList) {
      that.setData({
        changeDeliveryPointList: false
      });
      return false;
    }
    var delivery_sort = that.data.delivery_sort;
    var point_data = that.data.point_data;
    var select_point_data = [];
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].is_receive == 0) {
        var shop_time = point_data[i].shop_time;
        if (moment(shop_time).isValid()) {
          shop_time = moment(point_data[i].shop_time).format('MM月DD日 HH时mm分')
        } else {
          shop_time = '';
        }
        select_point_data.push({
          "id": point_data[i].ID,
          "name": point_data[i].name,
          "point_sort": Number(point_data[i].point_sort),
          "shop_time": shop_time
        });
      }
    }
    select_point_data.sort(function (a, b) {
      return a.point_sort > b.point_sort ? 1 : -1;
    });
    that.setData({
      select_point_data: select_point_data,
      spd_height: 37 * (select_point_data.length + 1),
      changeDeliveryPointList: true
    })
    //console.log(select_point_data)
  },
  selectChangeDeliveryPoint: function (e) {
    var that = this;
    if (e.currentTarget.id == 'change_delivery_close') {
      that.setData({
        changeDeliveryPointList: false
      });
      return false;
    }
    var delivery_sort = 0;
    var point_data = that.data.point_data,
      receive_point_data = [];
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].is_receive == 1) {
        receive_point_data.push(point_data[i])
      }
    }
    delivery_sort = receive_point_data.length;
    //已经签收的按时间排序
    receive_point_data.sort(function (a, b) {
      return a.receive_time.localeCompare(b.receive_time);
    });
    var select_point_data = that.data.select_point_data,
      _point_update = new Array(),
      index = 0,
      sort = 1;
    for (var i = 0; i < receive_point_data.length; i++) {
      _point_update[index] = "(" + receive_point_data[i].ID + "," + sort + ")";
      sort++;
      index++;
    }
    for (var i = 0; i < select_point_data.length; i++) {
      if (select_point_data[i].id == e.currentTarget.id) {
        _point_update[index] = "(" + e.currentTarget.id + "," + sort + ")";
        sort++;
        index++;
      }
    }
    for (var i = 0; i < select_point_data.length; i++) {
      if (select_point_data[i].id != e.currentTarget.id) {
        _point_update[index] = "(" + select_point_data[i].id + "," + sort + ")";
        sort++;
        index++;
      }
    }
    var _point_update = _point_update.join(",");
    console.log(_point_update)
    wx.showLoading({
      title: '更新配送顺序...',
    });
    util.putData("changePointSort", {
      sort: _point_update
    }, function (res, error) {
      console.log(res);
      console.log(error)
      if (error) {
        wx.hideLoading();
        wx.showToast({
          title: '更新失败',
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.hideLoading();
        wx.showToast({
          title: '更新成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            that.setData({
              changeDeliveryPointList: false
            })
            that.initMap(that.data.orderId);
          }
        });
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '更新失败',
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  flowDelivery: function (e) {
    var that = this;
    var ID = e.currentTarget.dataset.ID;
    var no_delivery_point = that.data.no_delivery_point;
    for (var i = 0; i < no_delivery_point.length; i++) {
      if (no_delivery_point[i].ID == ID) {
        wx.setStorage({
          key: "no_delivery_point",
          data: no_delivery_point[i],
          success: function () {
            wx.navigateTo({
              url: '/pages/driver/order_delivery'
            })
          }
        })
      }
    }
  },
  flowOption: function (e) {
    var that = this;
    if (that.data.submiting == true) {
      return false;
    }

    that.setData({
      submiting: true,
      current_status_text: '提交中...'
    });

    var orderId = that.data.orderId;
    var delivery_data = that.data.delivery_data;
    var current_status = that.data.current_status;
    var delivery_sort = that.data.all_point_number_already;
    //不计回程的操作
    if (delivery_sort > that.data.point_data.length - 1) {
      delivery_sort = that.data.point_data.length - 1
    }
    var state = "reach";
    if (that.data.all_point_number_already == that.data.point_data.length - 1) {
      state = "delivery_end";
    }
    if (that.data.delivery_status == 'delivery_end') {
      state = "end";
    }
    console.log(state)

    var currentPoint = that.data.currentPoint;
    var _type = currentPoint.type;
    var point_name = currentPoint.name;
    var point_id = currentPoint.point_id;
    var delivery_point = that.data.delivery_point;
    wx.showLoading({
      title: '提交中...'
    });
    that.nextPointReachTime(function (distance) {
      if (currentPoint.distance_exception == 2) {
        wx.hideLoading();
        wx.showModal({
          title: "提交失败",
          content: "请等待调度审核距离异常",
          success: function (res) {
            if (res.confirm) {
              that.initMap(that.data.orderId);
            }
          }
        })
        return false;
      }
      // console.log(distance)
      // console.log(1111111111111)
      // console.log(Number(delivery_data.reach_distance_limit) > 0)
      // console.log(distance > Number(delivery_data.reach_distance_limit))
      // console.log(currentPoint.distance_exception == 0)
      // console.log(!currentPoint.isreturn_ignore_distance_exception)
      // console.log(22222222222222)
      if (Number(delivery_data.reach_distance_limit) > 0 &&
        distance > Number(delivery_data.reach_distance_limit) &&
        currentPoint.distance_exception != 1 && !currentPoint.isreturn_ignore_distance_exception) {
        wx.hideLoading();
        wx.showModal({
          title: "提交失败",
          content: "你距离目的地【" + currentPoint.name + "】的距离超过一公里（" + (distance / 1000).toFixed(2) + "公里），请到达目的地后再操作。如已到达目的地，请检查GPS是否已经打开。如因手机问题可申请临时通过，但会被记录，一旦核查作假，将会处罚。",
          cancelText: "申请通过",
          confirmText: "重新操作",
          success: function (res) {
            if (res.confirm) {
              that.setData({
                submiting: false,
                current_status_text: '重新提交'
              });
            } else if (res.cancel) {
              wx.showLoading({
                title: '提交申请中...'
              });
              util.postData("/atapi/delivery/process/exceptionAuthorize", {
                id: orderId,
                point_id: point_id,
                point_name: point_name,
                ID: currentPoint.ID,
                distance: (distance / 1000).toFixed(2) + "公里",
                type: 'distance',
                CO_ID: app.globalData.CO_ID
              }, function (res, error) {
                console.log(res);
                console.log(error)
                if (error) {
                  wx.hideLoading();
                  wx.showToast({
                    title: res.data.data,
                    image: '/images/wrong.svg',
                    duration: 2000
                  });
                  return false;
                }
                if (res.data.success) {
                  wx.hideLoading();
                  that.setData({
                    submiting: false,
                    current_status_text: '重新提交'
                  });
                  wx.showModal({
                    title: "申请成功",
                    content: "等待项目负责人审核授权，你将收到授权结果通知。如果授权成功，再次操作达到配送点将临时不限制距离范围",
                    showCancel: false,
                    confirmText: "确定",
                    success: function (res) {

                    }
                  });
                } else {
                  wx.hideLoading();
                  wx.showToast({
                    title: res.data.data,
                    image: '/images/wrong.svg',
                    duration: 2000
                  });
                }
              });
            }
          }
        });
        return false;
      }
      util.postData("/sys/form/commonUpdate", {
        "formId": "6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
        "list_id": "",
        "data": [{
          "dataId": orderId,
          "target": {
            "driver_status": state,
            "delivery_point": delivery_point,
            "delivery_sort": delivery_sort
          }
        }],
        "condition": ""
      }, function (res, error) {
        console.log(res);
        console.log(error)
        if (error) {
          wx.hideLoading();
          wx.showToast({
            title: '更新状态失败',
            image: '/images/wrong.svg',
            duration: 2000
          });
          return false;
        }
        if (res.data.success) {
          util.postData("/sys/form/commonUpdate", {
            "formId": "1188A557-71F4-47EB-96C8-8AFE6E866C11",
            "list_id": "",
            "data": [{
              "dataId": currentPoint.ID,
              "target": {
                "is_receive": 1,
                "receive_time": moment().format('YYYY-MM-DD HH:mm:ss')
              }
            }],
            "condition": ""
          }, function (res, error) {
            wx.hideLoading();
            var exception = app.timeException(currentPoint.loading_time, 0);
            //轨迹
            var trace_title = "到达：" + point_name;
            if (that.data.isReturn == 1 && that.data.all_point_number_already == that.data.point_data.length) {
              trace_title = "返仓：" + point_name;
              app.updateDriverTrace(orderId, trace_title, "司机（" + delivery_data.driver_name + "）已驾驶车辆（" + delivery_data.plate + "）已到达【" + point_name + "】", that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, delivery_point.indexOf("S") > -1 ? point_id : '', delivery_point.indexOf("W") > -1 ? point_id : '', exception, 'reach', distance);

            }
            if (that.data.all_point_number_already < that.data.point_data.length) {
              app.updateDriverTrace(orderId, trace_title, "司机（" + delivery_data.driver_name + "）已驾驶车辆（" + delivery_data.plate + "）已到达【" + point_name + "】", that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, delivery_point.indexOf("S") > -1 ? point_id : '', delivery_point.indexOf("W") > -1 ? point_id : '', exception, 'reach', distance);
            }
            if (state == 'end' || (that.data.isReturn == 0 && that.data.all_point_number_already == that.data.point_data.length - 1)) {
              setTimeout(function () {
                app.updateDriverTrace(orderId, "全程配送结束", "全程配送完毕（本运单已经全程配送完毕，任务结束）。",
                  that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, '', '', 0, 'end', distance);
                wx.showModal({
                  title: "全程配送结束",
                  content: "全程配送完毕（本运单已经全程配送完毕，任务结束）。",
                  showCancel: false,
                  confirmText: "确定",
                  success: function (res) {
                    that.initMap(orderId);
                  }
                });
              }, 500)
            }
            wx.showToast({
              title: '已通知发货点',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.initMap(orderId);
              }
            });
          })

        } else {
          wx.hideLoading();
          wx.showToast({
            title: '更新状态失败',
            image: '/images/wrong.svg',
            duration: 2000
          });
        }
        setTimeout(function () {
          that.setData({
            submiting: false
          });
        }, 2000)
      });
    })
  },
  nextPointReachTime: function (callback) {
    console.log('nextPointReachTime')
    var that = this;
    var currentPoint = that.data.currentPoint;
    var getLBSTime = 0,
      getLBSResult = false;
    var lsbtInterval = setInterval(function () {
      if (getLBSResult) {
        clearInterval(lsbtInterval);
      }
      if (getLBSResult == false && getLBSTime > 30) {
        wx.showModal({
          title: "温馨提示",
          content: "获取你的位置失败，请确认打开手机的位置信息（不同手机叫法不一样，或者定位服务，或者GPS。）。如果还是获取失败，请到附件空地上，避免障碍物影响到卫星信号，导致获取位置失败。",
          showCancel: false,
          confirmText: "确定",
          success: function (res) {

          }
        });
        clearInterval(lsbtInterval);
      }
      getLBSTime++;
      console.log(getLBSTime)
    }, 1000);
    that.getLocation(function (longitude, latitude) {
      getLBSResult = true;
      try {
        let warehouse = (app.globalData.latitude ? app.globalData.latitude : latitude) + ',' + (app.globalData.longitude ? app.globalData.longitude : longitude)
        let shop = [currentPoint.latitude + ',' + currentPoint.longitude]
        shop.push()
        util.postData("/tencent/map/driving", {
          "isReturn": false,
          "shop": shop,
          "warehouse": warehouse,
          "warehouse_id": "",
          "toPoint": ""
        }, function (res) {
          var distance = 0,
            duration = 0;
          if (res.data.success) {
            if (res.data?.result?.result?.routes?.length > 0) {
              distance = Number(res.data.result.result.routes[0].distance / 1000).toFixed(1)
              duration = Number(res.data.result.result.routes[0].duration / 60).toFixed(2)
            }
            var _hour = Math.floor(duration / 60);
            var _minute = Number(duration - _hour * 60).toFixed(0);
            that.setData({
              target_address: "目的地：" + currentPoint.address,
              target_distance: "距离目的地大约" + Number(distance / 1000).toFixed(1) + "公里，预计耗时：" + _hour + "时" + _minute + "分"
            })
          }
          if (callback) callback(distance);
        });
      } catch (e) {};
    });
  },
  geocode: function () {
    var that = this;
    that.getLocation(function (longitude, latitude) {
      util.getData("/xypapi/map/routerCalculate/geocode", {
        longitude: longitude,
        latitude: latitude
      }, function (res) {
        if (res.data.success) {
          that.setData({
            target_address: "你所在位置：" + res.data.data,
            target_distance: '无目标计算距离'
          })
        }
      });
    });
  },
  //运单据
  submitDeliveryDocs: function () {
    var that = this;
    var delivery_picture = that.data.deliveryDocsImgList;
    if (delivery_picture.length == 0) {
      wx.showToast({
        title: '请上传单据',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...'
    });
    var _delivery_picture = [];
    for (var i = 0; i < delivery_picture.length; i++) {
      if (delivery_picture[i] && delivery_picture[i] != 'null' && delivery_picture[i] != 'undefined') {
        _delivery_picture.push(delivery_picture[i]);
      }
    }
    util.putData("/atapi/delivery/process/deliveryDocs", {
      id: that.data.orderId,
      delivery_picture: _delivery_picture.join(",")
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  //路桥费
  submitTollfee: function () {
    var that = this;
    var tollfee = that.data.tollfee;
    var tollfee_docs = that.data.tollfeeImgList;
    if (tollfee == 0) {
      wx.showToast({
        title: '请填写路桥费',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    if (tollfee_docs.length == 0) {
      wx.showToast({
        title: '请上传单据',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...'
    });
    var _tollfee_docs = [];
    for (var i = 0; i < tollfee_docs.length; i++) {
      if (tollfee_docs[i] && tollfee_docs[i] != 'null' && tollfee_docs[i] != 'undefined') {
        _tollfee_docs.push(tollfee_docs[i]);
      }
    }
    util.putData("/atapi/delivery/process/tollfee", {
      id: that.data.orderId,
      tollfee: tollfee,
      tollfee_docs: _tollfee_docs.join(",")
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  //停车速费
  submitParkingfee: function () {
    var that = this;
    var parkingfee = that.data.parkingfee;
    var parkingfee_docs = that.data.parkingfeeImgList;
    if (parkingfee == 0) {
      wx.showToast({
        title: '请填写停车费',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    if (parkingfee_docs.length == 0) {
      wx.showToast({
        title: '请上传单据',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...'
    });
    var _parkingfee_docs = [];
    for (var i = 0; i < parkingfee_docs.length; i++) {
      if (parkingfee_docs[i] && parkingfee_docs[i] != 'null' && parkingfee_docs[i] != 'undefined') {
        _parkingfee_docs.push(parkingfee_docs[i]);
      }
    }
    util.putData("/atapi/delivery/process/parkingfee", {
      id: that.data.orderId,
      parkingfee: parkingfee,
      parkingfee_docs: _parkingfee_docs.join(",")
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  //接驳费
  submitDeliveryThirdPartyFee: function () {
    var that = this;
    var deliveryThirdParty_income = that.data.deliveryThirdParty_income;
    var deliveryThirdParty_pay = that.data.deliveryThirdParty_pay;
    // if (isNaN(Number(deliveryThirdParty_income)) == true || deliveryThirdParty_income == 0) {
    //   wx.showToast({ title: '请填写费用金额', image: '/images/wrong.svg', duration: 2000 });
    //   return false;
    // }
    // if (!deliveryThirdParty_pay) {
    //   wx.showToast({ title: '请填写费用名目', image: '/images/wrong.svg', duration: 2000 });
    //   return false;
    // }

    wx.showLoading({
      title: '提交中...'
    });
    util.putData("/atapi/delivery/process/deliveryThirdPartyFee", {
      id: that.data.orderId,
      deliveryThirdParty_income: deliveryThirdParty_income,
      deliveryThirdParty_pay: deliveryThirdParty_pay,
      packageList: JSON.stringify(that.data.packageList),
      user_id: app.globalData.user_id,
      CO_ID: app.globalData.CO_ID
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  //其他费用
  submitOtherfee: function () {
    var that = this;
    var otherfeeName = that.data.otherfeeName;
    var otherfee = that.data.otherfee;
    if (isNaN(Number(otherfee)) == true || otherfee == 0) {
      wx.showToast({
        title: '请填写费用金额',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    if (!otherfeeName) {
      wx.showToast({
        title: '请填写费用名目',
        image: '/images/wrong.svg',
        duration: 2000
      });
      return false;
    }
    wx.showLoading({
      title: '提交中...'
    });
    util.putData("/atapi/delivery/process/otherfee", {
      id: that.data.orderId,
      otherfeeName: otherfeeName,
      otherfee: otherfee
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  qrcodeModeFlow: function (_shop) {
    var that = this;
    var _form_rule = [],
      form_rule = String(_shop.form_rule).split(",");
    for (var j in form_rule) {
      var _item = String(form_rule[j]).split("|");
      _form_rule.push({
        "id": "FR" + j,
        "name": _item[0],
        "value": _item[1]
      });
    }
    that.setData({
      form_rule: _form_rule,
      form_rule_data: _shop.form_rule
    });
    wx.hideLoading();
    var content = '配送点是：' + _shop.name;
    if (_shop.warehouse) {
      content = '请确认后输入仓库交接箱框数量和现场相片';
    }
    wx.showModal({
      title: '识别成功',
      content: content,
      confirmText: '确认',
      cancelText: '重新扫描',
      success: function (res) {
        if (res.confirm) {
          that.setData({
            delivery_item_form: true,
            currentShop: _shop,
            mapHidden: true,
            submiting: false
          })
        } else if (res.cancel) {
          wx.hideLoading()
          that.setData({
            current_status_text: "扫描二维码",
            submiting: false
          });
        }
      }
    })
  },
  controltap: function (e) {
    console.log(e)
    var that = this;
    if (e.controlId == 1) {

    } else if (e.controlId == 2) {
      wx.makePhoneCall({
        phoneNumber: '4009971568'
      })
    } else if (e.controlId > 9 && e.controlId < 40) {
      var current_point_data = that.data.point_data[e.controlId - 10];
      wx.showModal({
        title: '配送点信息',
        content: '名称：' + current_point_data.name + '\n地址：' + current_point_data.address + '\n联系人：' + current_point_data.user_name,
        cancelText: '关闭',
        confirmText: '致电配送点',
        success: function (res) {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: current_point_data.user_phone
            })
          }
        }
      })
    } else if (e.controlId > 40 && e.controlId < 60) {

    }
  },
  chooseDeliveryImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var deliveryImageList = that.data.deliveryImageList;
    var deliveryImageListCompress = that.data.deliveryImageListCompress;
    try {
      var formData = {
        'id': that.data.orderId,
        'ID': that.data.currentShop.ID,
        'type': 'shop'
      };
    } catch (e) {}
    if (type && type == 'tollfee') {
      deliveryImageList = that.data.tollfeeImgList;
      deliveryImageListCompress = that.data.tollfeeImgListCompress;
      formData = {
        'id': that.data.orderId,
        'type': 'tollfee'
      };
    }
    if (type && type == 'parkingfee') {
      deliveryImageList = that.data.parkingfeeImgList;
      deliveryImageListCompress = that.data.parkingfeeImgListCompress;
      formData = {
        'id': that.data.orderId,
        'type': 'parkingfee'
      };
    }
    if (type && type == 'delivery_picture') {
      deliveryImageList = that.data.deliveryDocsImgList;
      deliveryImageListCompress = that.data.deliveryDocsImgListCompress;
      formData = {
        'id': that.data.orderId,
        'type': 'delivery_picture'
      };
    }
    wx.chooseMedia({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        // that.setData({
        //   modalName: 'uploadModal',
        //   progress: 0,
        //   totalBytesSent: 0,
        //   totalBytesExpectedToSend: 0
        // })
        formData.picture = JSON.stringify(deliveryImageList);
        formData.picture_compress = JSON.stringify(deliveryImageListCompress);
        that.uploadTask = wx.uploadFile({
          url: app.server + '/atapi/delivery/process/uploadDeliveryScene',
          header: {
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: formData,
          success: function (res) {
            var data = JSON.parse(res.data);
            console.log(data)
            wx.hideLoading();
            if (data.success) {
              deliveryImageList.push(data.data);
              deliveryImageList = util.arrayDeleteEmpty(deliveryImageList);
              deliveryImageListCompress.push(data.compress);
              deliveryImageListCompress = util.arrayDeleteEmpty(deliveryImageListCompress);

              console.log(deliveryImageList)
              console.log(deliveryImageListCompress)
              if (type == 'tollfee') {
                that.setData({
                  tollfeeImgList: deliveryImageList,
                  tollfeeImgListCompress: deliveryImageListCompress
                });
              } else if (type == 'parkingfee') {
                that.setData({
                  parkingfeeImgList: deliveryImageList,
                  parkingfeeImgListCompress: deliveryImageListCompress
                });
              } else if (type == 'delivery_picture') {
                that.setData({
                  deliveryDocsImgList: deliveryImageList,
                  deliveryDocsImgListCompress: deliveryImageListCompress
                });
              } else {
                that.setData({
                  deliveryImageList: deliveryImageList,
                  deliveryImageListCompress: deliveryImageListCompress
                });
              }
            } else {
              wx.showToast({
                title: "上传失败",
                image: '/images/wrong.png',
                duration: 2000
              });
            }
          },
          complete: function () {
            //wx.hideLoading();
            // that.setData({
            //   modalName: ''
            // })
          }
        })
        // that.uploadTask.onProgressUpdate((res) => {
        //   that.setData({
        //     progress: res.progress,
        //     totalBytesSent: Number(res.totalBytesSent / 1000 / 1000).toFixed(3),
        //     totalBytesExpectedToSend: Number(res.totalBytesExpectedToSend / 1000 / 1000).toFixed(3)
        //   })
        // })

      }
    })
  },
  cannelUpload(e) {
    this.setData({
      modalName: null
    })
    this.uploadTask.abort()
  },
  DelImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = [];
    var imgListCompress = [];
    if (type && type == 'tollfee') {
      imgList = that.data.tollfeeImgList;
      imgListCompress = that.data.tollfeeImgListCompress;
    }
    if (type && type == 'parkingfee') {
      imgList = that.data.parkingfeeImgList;
      imgListCompress = that.data.parkingfeeImgListCompress;
    }
    if (type && type == 'delivery_picture') {
      imgList = that.data.deliveryDocsImgList;
    }
    var url = imgList[index];
    var urlCompress = imgListCompress[index];

    wx.showModal({
      title: '温馨提示',
      content: '确定要删除图片吗？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });
          if (url == '') {
            if (imgList.length == 1) {
              imgList = [];
              imgListCompress = [];
            } else {
              imgList.splice(index, 1);
              imgListCompress.splice(index, 1);
            }
            if (type && type == 'tollfee') {
              that.setData({
                tollfeeImgList: imgList,
                tollfeeImgListCompress: imgListCompress
              })
            }
            if (type && type == 'parkingfee') {
              that.setData({
                parkingfeeImgList: imgList,
                parkingfeeImgListCompress: imgListCompress
              })
            }
            if (type && type == 'delivery_picture') {
              that.setData({
                deliveryDocsImgList: imgList
              })
            }
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000,
              success: function () {

              }
            });
            return false;
          }
          if (imgList.length == 1) {
            imgList = [];
            imgListCompress = [];
          } else {
            imgList = util.arrayDeleteWithIndex(imgList, index, 1);
            imgListCompress = util.arrayDeleteWithIndex(imgListCompress, index, 1);
          }
          util.putData("/atapi/delivery/process/deleteFile", {
            url: url,
            delivery: that.data.orderId,
            urlCompress: urlCompress,
            imgListCompress: imgListCompress.join(','),
            imgList: imgList.join(','),
            type: type
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: '删除失败',
                image: '/images/wrong.svg',
                duration: 2000
              });
              return false;
            }
            if (res.data.success) {
              if (type && type == 'tollfee') {
                that.setData({
                  tollfeeImgList: imgList,
                  tollfeeImgListCompress: imgListCompress
                })
              }
              if (type && type == 'parkingfee') {
                that.setData({
                  parkingfeeImgList: imgList,
                  parkingfeeImgListCompress: imgListCompress
                })
              }
              if (type && type == 'delivery_picture') {
                that.setData({
                  deliveryDocsImgList: imgList
                })
              }
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {

                }
              });
            }
          });
        }
      }
    });

  },
  previewImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var current = e.currentTarget.dataset.url
    var deliveryImageList = that.data.deliveryImageList;
    if (type && type == 'tollfee') {
      deliveryImageList = that.data.tollfeeImgList;
    }
    if (type && type == 'parkingfee') {
      deliveryImageList = that.data.parkingfeeImgList;
    }
    if (type && type == 'delivery_picture') {
      deliveryImageList = that.data.deliveryDocsImgList;
    }
    if (current.indexOf('http') == -1) {
      current = app.server + current;
    }
    if (deliveryImageList.length > 0) {
      for (var i = 0; i < deliveryImageList.length; i++) {
        if (String(deliveryImageList[i]).indexOf('http') == -1) {
          deliveryImageList[i] = app.server + deliveryImageList[i];
        }
      }
    }
    wx.previewImage({
      current: current,
      urls: util.arrayDeleteEmpty(deliveryImageList)
    })
  },
  chooseDeliveryDocumentsImage: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var point_data = that.data.point_data,
      currentPoint = {};
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].ID == id) {
        currentPoint = point_data[i]
      }
    }

    wx.chooseMedia({
      count: 1,
      sizeType: ['original'], //, 'compressed'
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        var size = Number(res.tempFiles[0].size || 1024000) / 1024;
        console.log(size)
        wx.showLoading({
          title: '上传中...'
        });
        var formData = {
          'id': id,
          'picture': JSON.stringify(currentPoint.picture),
          'picture_compress': JSON.stringify(currentPoint.picture_compress)
        };
        if (size > 500) {
          wx.compressImage({
            src: res.tempFiles[0].tempFilePath, // 图片路径
            quality: 70,
            success: function (res) {
              console.log('压缩',res)
              var url = res.tempFilePath;
              that.uploadFile(url, formData, currentPoint, id)
            }
          })
        } else {
          console.log('不压缩')
          var url = res.tempFiles[0].tempFilePath;
          that.uploadFile(url, formData, currentPoint, id)
        }
      }
    })
  },
  uploadFile: function (url, formData, currentPoint, id) {
    var that = this;
    wx.uploadFile({
      url: app.server + '/commons/file/uploads',
      header: {
        'Authorization': app.globalData.token
      },
      filePath: url,
      name: 'file',
      formData: formData,
      success: function (res) {
        var data = JSON.parse(res.data);
        console.log(data)
        if (data.success) {
          currentPoint.picture.push(data.result[0]);
          //currentPoint.picture_compress.push(data.compress);
          console.log(currentPoint)
          var point_data = that.data.point_data;
          for (var i = 0; i < point_data.length; i++) {
            if (point_data[i].ID == id) {
              point_data[i] = currentPoint
            }
          }
          //更新到运单表
          util.postData("/sys/form/commonUpdate",{
            "formId":"1188A557-71F4-47EB-96C8-8AFE6E866C11",
            "data":[{
                "dataId":id,
                "target":{"picture":currentPoint.picture.join(',')}
            }],
            "condition":""
            }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              return false;
            }
            if (res.data.success) {
            }
          });
          that.setData({
            point_data: point_data
          })
        } else {
          wx.showToast({
            title: "上传失败",
            image: '/images/wrong.png',
            duration: 2000
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  DelDocsImg: function (e) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除图片吗？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });
          var id = e.currentTarget.dataset.id;
          var picture_compress = e.currentTarget.dataset.picture_compress
          var picture = e.currentTarget.dataset.picture;
          console.log(picture_compress)
          var point_data = that.data.point_data;
          var currentPoint = {};
          for (var i = 0; i < point_data.length; i++) {
            if (point_data[i].ID == id) {
              currentPoint = point_data[i];
              var _picture_compress = point_data[i].picture_compress;
              var _picture_compress_ = [];
              for (var j in _picture_compress) {
                if (_picture_compress[j] != picture_compress) {
                  _picture_compress_.push(_picture_compress[j])
                }
              }
              point_data[i].picture_compress = _picture_compress_;

              var _picture = point_data[i].picture;
              var _picture_ = [];
              for (var j in _picture) {
                if (_picture[j] != picture) {
                  _picture_.push(_picture[j])
                }
              }
              point_data[i].picture = _picture_;
            }
          }
          that.setData({
            point_data: point_data
          })
          util.putData("/atapi/delivery/process/deleteDocsFile", {
            id: id,
            url: picture_compress,
            url2: picture,
            picture_compress: currentPoint.picture_compress.join(','),
            picture: currentPoint.picture.join(',')
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: '删除失败',
                image: '/images/wrong.svg',
                duration: 2000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {

                }
              });
            } else {
              wx.showToast({
                title: '删除失败',
                image: '/images/wrong.svg',
                duration: 2000
              });
            }
          });
        }
      }
    })

  },
  previewDocsImage: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.id;
    var point_data = that.data.point_data;
    var urls = [];
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].ID == id) {
        urls = point_data[i].picture;
      }
    }
    for (var i in urls) {
      if (String(urls[i]).indexOf('http') == -1) {
        urls[i] = that.data.server + urls[i];
      }
    }
    wx.previewImage({
      current: url,
      urls: urls
    })
  },
  delivery_item_form_close: function () {
    wx.redirectTo({
      url: '/pages/driver/currentOrder?id=' + this.data.orderId
    })
  },
  bindDeliveryFormInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id),
      item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
    if (item.indexOf("FR") > -1) {
      var form_rule = that.data.form_rule;
      for (var i = 0; i < form_rule.length; i++) {
        if (form_rule[i].id == item) {
          form_rule[i].value = e.detail.value;
          break;
        }
      }
      that.setData({
        form_rule: form_rule
      });
      that.calculateTotalFormRule();
    }
  },
  calculateTotalFormRule: function () {
    var that = this;
    var form_rule = that.data.form_rule,
      _form_rule = new Array();
    for (var i = 0; i < form_rule.length; i++) {
      _form_rule[i] = form_rule[i].name + "|" + form_rule[i].value;
    }
    that.setData({
      form_rule_data: _form_rule.join(",")
    })
  },
  delivery_item_form_ok: function () {
    var that = this;
    if (that.data.submiting) {
      return false;
    }
    wx.showLoading({
      title: '提交中...'
    });
    that.setData({
      submiting: true,
      current_status_text: '提交中...'
    });

    var orderId = that.data.orderId;
    var delivery_data = that.data.delivery_data;
    var point_data = that.data.point_data;
    var currentShop = that.data.currentShop;
    var receive_number = 0;
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].is_receive == 1) {
        receive_number++;
      }
    }
    var state = (receive_number == point_data.length - 1 ? "end" : "finish");
    var delivery_point = "S" + currentShop.shop;
    if (currentShop.warehouse) {
      delivery_point = "W" + currentShop.warehouse;
      state = "finish";
    }
    //配送结束
    util.putData("driverState", {
      state: state,
      id: orderId,
      delivery_point: delivery_point,
      delivery_sort: currentShop.point_sort,
      ID: currentShop.ID,
      form_rule_data: that.data.form_rule_data
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: '更新状态失败',
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        //轨迹
        if (state == 'end') {
          //app.socket.emit('deliveryEnd', { iotbox: that.data.iotbox, order: orderId });
          app.updateDriverTrace(orderId, "交/补货完毕【" + currentShop.name + "】", "已完成配送点交/补货，准备发往下一点", that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, currentShop.shop, '', 0, state, function () {
            app.updateDriverTrace(orderId, "全程配送结束", "全程配送完毕（本运单已经全程配送完毕，任务结束）。",
              that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, '', '', 0, 'end');
            wx.showToast({
              title: '全程配送结束',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/driver/summary?id=' + orderId
                  });
                }, 2000);
              }
            });
          });

        } else if (currentShop.warehouse) {
          app.updateDriverTrace(orderId, "车辆已离仓【" + currentShop.name + "】", "开始配送", that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, '', currentShop.warehous, 0, state, function () {});
        } else {
          app.updateDriverTrace(orderId, "交/补货完毕【" + currentShop.name + "】", "已完成配送点交/补货，准备发往下一点", that.data.latitude + ',' + that.data.longitude, that.data.temperature, that.data.humidity, currentShop.shop, '', 0, state, function () {});
        }
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/driver/currentOrder?id=' + orderId
              });
            }, 2000);
          }
        });
      } else {
        that.setData({
          submiting: false
        });
        wx.showToast({
          title: '更新状态失败',
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
  changeAgreeRequirement: function (e) {
    if (e.detail.value == '1') {
      this.setData({
        is_agree_requirement: true
      })
    } else {
      this.setData({
        is_agree_requirement: false
      })
    }
  },
  delivery_form_close: function () {
    var that = this;
    var delivery_data = that.data.delivery_data;
    wx.showModal({
      title: '温馨提示',
      content: '拒绝接单将会在司机星级评定中扣分，在仓库要求到仓时间2小时前不操作视为拒单。确定请选择拒单原因。',
      success(res) {
        if (res.confirm) {
          var _list = ['精力不济', '有私有业务', '和其他配送时间冲突', '出现意外，喝酒、生病和事故等', '私事请假', '今日不想工作'];
          wx.showActionSheet({
            itemList: _list,
            success(res) {
              var reason = _list[res.tapIndex];
              util.postData("rejectDelivery", {
                orderId: that.data.orderId,
                reason: reason,
                NO: delivery_data.NO,
                driver: delivery_data.driver_name,
                plate: delivery_data.plate,
                path_name: delivery_data.path_name || '临时路线',
                wh_name: delivery_data.wh_name
              }, function (res) {
                console.log(res.data.data)
                if (res.data.success) {
                  wx.showToast({
                    title: res.data.data,
                    icon: 'success',
                    duration: 2000,
                    success: function () {
                      setTimeout(function () {
                        wx.redirectTo({
                          url: '/pages/driver/orderList'
                        });
                      }, 2000);
                    }
                  });
                } else {
                  wx.showToast({
                    title: res.data.data,
                    image: '/images/wrong.png',
                    duration: 2000
                  });
                }
              });
            },
            fail(res) {
              console.log(res.errMsg)
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },
  delivery_form_ok: function () {
    var that = this;
    var delivery_data = that.data.delivery_data;
    var is_agree_requirement = this.data.is_agree_requirement;
    if (!is_agree_requirement) {
      wx.showToast({
        title: "请先选择同意",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    } else {
      that.setData({
        is_agree_requirement: false
      })
      util.postData("acceptDelivery", {
        orderId: that.data.orderId,
        driver_phone: delivery_data.driver_phone,
        driver: delivery_data.driver_name,
        plate: delivery_data.plate,
        path_name: delivery_data.path_name || '临时路线',
        wh_name: delivery_data.wh_name
      }, function (res) {
        console.log(res.data.data)
        if (res.data.success) {
          wx.showToast({
            title: res.data.data,
            icon: 'success',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/driver/currentOrder?id=' + that.data.orderId
                });
              }, 2000);
            }
          });
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 2000
          });
        }
      });
    }
  },
  changeAgreeUndertaking: function (e) {
    if (e.detail.value == '1') {
      this.setData({
        is_agree_undertaking: true
      })
    } else {
      this.setData({
        is_agree_undertaking: false
      })
    }
  },
  undertaking_close: function () {
    wx.redirectTo({
      url: '/pages/driver/orderList'
    });
  },
  undertaking_ok: function () {
    var that = this;
    var is_agree_undertaking = this.data.is_agree_undertaking;
    if (!is_agree_undertaking) {
      wx.showToast({
        title: "请先同意要求",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    } else {
      that.setData({
        is_agree_undertaking: false
      })
      util.postData("agreeUndertaking", {
        orderId: that.data.orderId
      }, function (res) {
        console.log(res.data.data)
        if (res.data.success) {
          wx.showToast({
            title: res.data.data,
            icon: 'success',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                wx.redirectTo({
                  url: '/pages/driver/currentOrder?id=' + that.data.orderId
                });
              }, 2000);
            }
          });
        } else {
          wx.showToast({
            title: res.data.data,
            image: '/images/wrong.png',
            duration: 2000
          });
        }
      });
    }
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id),
      item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  bindblur: function (e) {
    var item = String(e.currentTarget.id),
      item_value = {};
    var value = e.detail.value;
    this.setData(item_value);
    if (item == 'packages_expect') {
      var packageList = this.data.packageList;
      var _packages_expect = 0;
      for (var i = 0; i < packageList.length; i++) {
        _packages_expect += Number(packageList[i].package) || 0;
      }
      if (value != _packages_expect) {
        wx.showToast({
          title: '总数量不符',
          image: '/images/wrong.png',
          duration: 2000
        });
        // item_value[item] = _packages_expect;
        // this.setData(item_value);
      }
    }
  },
  bindLoadingInput: function (e) {
    var that = this;
    //货品信息数组
    var packageList = that.data.packageList;
    //当前输入值，如果不为数字则为0
    var value = isNaN(e.detail.value) ? 0 : e.detail.value;
    var _id = String(e.currentTarget.id).split("_");
    //收货点的ID
    var pid = _id[0];
    //货物类型的ID
    var id = _id[1];
    //总框数
    var packages = 0;
    for (var i = 0; i < packageList.length; i++) {
      //处理当前输入的货品数量
      if (packageList[i].id == pid) {
        //每个收货点的各类货品计算规则和数量
        var loadingRule = packageList[i].loadingRule;
        //当前收货点数量
        var currentNumber = 0;

        var loading_rule = new Array();
        //找出当前收货点计算规则中当前货品，设置数量
        for (var j = 0; j < loadingRule.length; j++) {
          console.log(loadingRule[j].id + "|" + id + "|" + pid)
          if (loadingRule[j].id == id) {
            loadingRule[j].number = value;
          }
          //计算当前收货点的数量
          currentNumber += Number(loadingRule[j].number) * Number(loadingRule[j].ratio);
          //拼接当前收货点的计算规则字符串
          loading_rule[j] = loadingRule[j].name + "|" + loadingRule[j].ratio + "|" + loadingRule[j].number;

          console.log(loading_rule[j])
        }
        //重新赋值当前收货点的计算规则和数量
        packageList[i].loadingRule = loadingRule;
        packageList[i].package = currentNumber.toFixed(2);
        packageList[i].goodsInfo = loading_rule.join(",");
      }
      packages += Number(packageList[i].package);
    }

    that.setData({
      packageList: packageList,
      packages: packages.toFixed(2)
    });

    return value;
    //that.calculateTotalLoading();
  },
  bindPackageInput: function (e) {
    var that = this;
    var packageList = that.data.packageList,
      packages = 0,
      unload_box = 0,
      back_box = 0,
      return_package = 0,
      deliveryThirdParty_income = 0,
      deliveryThirdParty_pay = 0;

    var value = isNaN(e.detail.value) ? 0 : e.detail.value;
    var id = String(e.currentTarget.id);
    var _id = id.split('_')

    for (var i = 0; i < packageList.length; i++) {
      if (packageList[i].id == id) {
        packageList[i].package = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'unloadbox') {
        packageList[i].unload_box = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'backbox') {
        packageList[i].back_box = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'returnpackage') {
        packageList[i].return_package = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'deliveryThirdPartyincome') {
        packageList[i].deliveryThirdParty_income = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'deliveryThirdPartypay') {
        packageList[i].deliveryThirdParty_pay = value;
      }
      packages += Number(packageList[i].package || 0);
      unload_box += Number(packageList[i].unload_box || 0);
      back_box += Number(packageList[i].back_box || 0);
      return_package += Number(packageList[i].return_package || 0);
      deliveryThirdParty_income += Number(packageList[i].deliveryThirdParty_income || 0);
      deliveryThirdParty_pay += Number(packageList[i].deliveryThirdParty_pay || 0);
    }

    that.setData({
      packageList: packageList,
      packages: packages.toFixed(2),
      unload_box: unload_box.toFixed(2),
      back_box: back_box.toFixed(2),
      return_package: return_package.toFixed(2),
      deliveryThirdParty_income: deliveryThirdParty_income.toFixed(2),
      deliveryThirdParty_pay: deliveryThirdParty_pay.toFixed(2)
    });

    return value;
  },
  bindGoodsInfoInput: function (e) {
    var that = this;
    var packageList = that.data.packageList;

    var value = e.detail.value;
    var id_goodsInfo = String(e.currentTarget.id).replace("_goodsInfo", "");
    var id_remark = String(e.currentTarget.id).replace("_remark", "");

    for (var i = 0; i < packageList.length; i++) {
      if (packageList[i].id == id_goodsInfo) {
        packageList[i].goodsInfo = value;
      }
      if (packageList[i].id == id_remark) {
        packageList[i].remark = value;
      }
    }

    that.setData({
      packageList: packageList
    });

    return value;
  },
  calculateTotalLoading: function () {
    var that = this;
    var loadingRule = that.data.loadingRule,
      _loading_rule = new Array(),
      packages_expect = 0;
    for (var i = 0; i < loadingRule.length; i++) {
      packages_expect += Number(loadingRule[i].number) * Number(loadingRule[i].ratio);
      _loading_rule[i] = loadingRule[i].name + "|" + loadingRule[i].ratio + "|" + loadingRule[i].number;
    }
    that.setData({
      loading_rule: _loading_rule.join(","),
      packages_expect: packages_expect
    })
  },
  loading_form_ok: function () {
    var that = this;
    if (!that.data.packages || that.data.packages == '') {
      wx.showToast({
        title: '请输入箱框总数',
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    console.log(11111)
    util.putData("deliveryPackage", {
      orderId: that.data.orderId,
      packages_expect: that.data.packages_expect || 0,
      packages: that.data.packages,
      volume: that.data.volume || 0,
      weight: that.data.weight || 0,
      unload_box: that.data.unload_box || 0,
      back_box: that.data.back_box || 0,
      return_package: that.data.return_package || 0,
      goodsValue: that.data.goodsValue || 0,
      packageList: JSON.stringify(that.data.packageList),
      user_id: app.globalData.user_id,
      CO_ID: app.globalData.CO_ID
    }, function (res, error) {
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            that.hideModal();
            // setTimeout(function () {
            //   wx.redirectTo({
            //     url: '/pages/driver/currentOrder?id=' + that.data.orderId
            //   });
            // }, 2000);
          }
        })
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  shopPicture: function () {
    var shop = false;
    try {
      shop = this.data.point_data[this.data.delivery_sort - 1].shop
    } catch (e) {}
    if (!shop) {
      wx.showToast({
        title: '暂无引导信息',
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/schedule/apps/shopPicture?show=true&id=' + this.data.point_data[this.data.delivery_sort - 1].shop
    })
  },
  gotoScan: function () {
    util.driverScan();
  },
  gotoHome: function () {
    wx.redirectTo({
      url: '/pages/driver/orderList'
    })
  },
  gotoVehicleTollfee: function () {
    wx.navigateTo({
      url: '/pages/vehicle/vehicle_tollfee?tab=3&id=' + this.data.vehicleId + '&delivery=' + this.data.orderId + '&path_name=' + this.data.path_name
    })
  },
  gotoVehicleParkingfee: function () {
    wx.navigateTo({
      url: '/pages/vehicle/vehicle_parkingfee?tab=24&id=' + this.data.vehicleId + '&delivery=' + this.data.orderId + '&path_name=' + this.data.path_name
    })
  }

})